package root.electronclass.electronclass.common.base;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.ToastUtils;
import root.electronclass.electronclass.R;
import root.electronclass.electronclass.common.dialog.HttpLoadingDialog;
import root.electronclass.electronclass.common.dialog.K12DialogHelper;
import root.electronclass.electronclass.common.util.ActivityManager;
import root.electronclass.electronclass.mvp.base.DialogViewModel;

import java.util.Date;


public abstract class BaseActivity extends FragmentActivity {
    public K12DialogHelper helper;
    public HttpLoadingDialog httpDialog;
    protected DialogViewModel mDialogViewModel;

    private DialogViewModel getViewModel() {
        return new ViewModelProvider(
                this,
                new ViewModelProvider.Factory() {
                    @NonNull
                    @Override
                    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                        return (T) new DialogViewModel();
                    }
                })
                .get(DialogViewModel.class);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        displayMetrics.scaledDensity = 1f;
        displayMetrics.density = 1f;

        ActivityManager.getInstance().addActivity(this);

        //设置系统语言，其他语言默认英文
        //Utils.setLocal();
        mDialogViewModel = getViewModel();
        mDialogViewModel.showProgressData.observe(
                this,
                showProgress -> {
                    onCompelet();
                });
        mDialogViewModel.showErrorData.observe(
                this,
                baseResponse -> {
                    onCompelet();
                    toast(baseResponse.getMsg());
                });
        mDialogViewModel.showExceptionData.observe(
                this,
                throwable -> {
                    onCompelet();
                    throwable.getMessage();
                    //抛出所有异常内容，可作为
                    toast(throwable.getMessage());

                });
    }

    public void showWaitingMessage() {
        if (httpDialog == null) {
            httpDialog = new HttpLoadingDialog(this, getString(R.string.loading_wait));
            httpDialog.setCanceledOnTouchOutside(false);
            httpDialog.setOnCancelListener(dialog -> finish());
            httpDialog.show();
        } else {
            httpDialog.show();
        }
    }



    public void dismissProgress() {
         if (httpDialog != null && httpDialog.isShowing()) {
            httpDialog.dismiss();
        }
    }

    private void newDialog(String message) {
        if (helper == null) {
            helper = new K12DialogHelper(this);
        }
        if (helper.getContext().equals(message) && helper.isShow()) {
            return;
        }
    }

    /**
     * 获取自己应用内部的版本名
     */
    public static String getVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    /**
     * 获取自己应用内部的版本名
     */
    public static int getVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int name = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    public void showDialogMessage(String res_icon, String message) {
        newDialog(message);
        helper.setContent(message);
        helper.setIcon(res_icon);
        helper.show();
    }

    public void showDialogMessage(String message) {
//        newDialog(message);
//        helper.setContent(message);
//        helper.setIcon(getResources().getString(R.string.icon_warning));
//        helper.show();
    }

    public void showDialogMessage(String message, int res) {
        newDialog(message);
        helper.setContent(message);
        helper.setIcon(getResources().getString(res));
        helper.show();
    }

    String msg = null;//弹框内容
    long time = 0;//上次弹框时间

    @UiThread
    public void toast(String msg) {
        if (msg == null || msg.isEmpty()) {
            return;
        }
        ToastUtils.showShort(msg);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (helper != null) {
            helper.dismiss();
        }
        ToastUtils.cancel();
        super.onDestroy();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            // 获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left
                    && event.getX() < right
                    && event.getY() > top
                    && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                // 使EditText触发一次失去焦点事件
                v.setFocusable(false);
                //                v.setFocusable(true); //这里不需要是因为下面一句代码会同时实现这个功能
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }

    /**
     * 网络请求完毕
     */
    public void onCompelet() {

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
